import Koa from "koa"
import bodyParser from "koa-bodyparser"
import Router from "koa-router"
import cors from "@koa/cors"
import { DataTypes, Sequelize,Op } from "sequelize"

const app = new Koa()
const router = new Router()
app.use(cors())
app.use(bodyParser())

const sequelize = new Sequelize('protectDb', 'root', '123456', {
    dialect: "mysql"
})

const Protect = sequelize.define('protect', {
    protectName: DataTypes.STRING,
    protectPrice: DataTypes.STRING,
    protectNum: DataTypes.INTEGER
})

//同步数据库，如果表存在则删除再创建
await sequelize.sync({ force: true })

//创建数据
await Protect.bulkCreate(
    [
        { protectName: "小米15", protectPrice: "5999￥", protectNum: 100 },
        { protectName: "小米平板", protectPrice: "4999￥", protectNum: 150 },
        { protectName: "双人沙发", protectPrice: "1999￥", protectNum: 200 }
    ]
)

//定义获取所有商品的路由
router.get("/protects", async (ctx) => {
    let protects;
    let keyword = ctx.request.query.keyword || ''//获取查询参数keyword
    console.log(keyword);
    
    if (keyword) {
        protects = await Protect.findAll({
            where: {
                [Op.or]: {
                    protectName: {
                        [Op.like]: `%${keyword}%`
                    },
                    protectPrice: {
                        [Op.like]: `%${keyword}%`
                    },
                    protectNum: {
                        [Op.like]: `%${keyword}%`
                    },
                }
            }
        })
    } else {
        protects = await Protect.findAll()
    }

    ctx.body = {
        code: 1000,
        msg: '请求成功',
        data: protects
    }
})

//定义获取单个商品的路由
router.get("/protect/:id", async (ctx) => {
    let id = ctx.params.id
    let protect = await Protect.findByPk(id)

    ctx.body = {
        code: 1000,
        msg: '请求成功',
        data: protect
    }
})

//定义删除商品路由
router.delete("/protect/:id", async (ctx) => {
    let id = ctx.params.id
    let protect = await Protect.destroy({where:{id}})

    ctx.body = {
        code: 1000,
        msg: '请求成功',
        data: protect
    }
})

//定义更新商品路由
router.put("/protect/:id",async(ctx)=>{
    let id = ctx.params.id
    let obj = ctx.request.body
    let protect = await Protect.update(obj,{where:{id}})
    ctx.body = {
        code:1000,
        msg:'请求成功',
        data:protect
    }
 })

 //定义添加商品路由
 router.post("/protect",async(ctx)=>{
    let obj = ctx.request.body
    let protect = await Protect.create(obj)
    ctx.body = {
        code:1000,
        msg:'请求成功',
        data:protect
    }
 })


 app.use(router.routes())
 let prot = 3000;
app.listen(prot);
console.log(`服务器运行于：http://localhost:${prot}`);
